package com.niodata.dp.monitor.core.task.dao;

import com.niodata.dp.monitor.core.task.entity.JobLogMapping;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface JobLogMappingMonitorMapper {

  @Select("select * from JOB_LOG_MAPPING where EXEC_ID=#{execId} and JOB_NAME=#{jobName} and LOG_TYPE='TASKLOG'")
  @ResultMap("jobLogResultMap")
  public JobLogMapping getJobLogByExecId(@Param("execId") String execId, @Param("jobName") String jobName);

  @Insert(
        "insert into JOB_LOG_MAPPING (TASK_NAME,JOB_NAME,EXEC_ID,YARN_APP_ID,YARN_ATTEMPT_ID,LOG_DIR,HOST_NAME,"
              + "HOST_ADDR,LOG_TYPE,CREATE_TIME) VALUES (#{jobLog.taskName},#{jobLog.jobName},"
              + "#{jobLog.execId},#{jobLog.yarnAppId},#{jobLog.yarnAttemptId},#{jobLog.logDir},#{jobLog.hostName},#{jobLog.hostAddr},"
              + "#{jobLog.logType},#{jobLog.createTime})")
  public void insert(@Param("jobLog") JobLogMapping jobLog);

  @Insert(
    "update JOB_LOG_MAPPING set LOG_DIR=#{jobLog.logDir},HOST_NAME=#{jobLog.hostName},HOST_ADDR=#{jobLog.hostAddr} where EXEC_ID=#{jobLog.execId}")
  public void update(@Param("jobLog") JobLogMapping jobLog);

  @Update("update JOB_LOG_MAPPING set YARN_ATTEMPT_ID = #{jobLog.yarnAttemptId} where "
        + " YARN_APP_ID = #{jobLog.yarnAppId} and LOG_DIR = #{jobLog.logDir}")
  public void updateAttemptId(@Param("jobLog") JobLogMapping jobLog);

  @Select("select * from JOB_LOG_MAPPING where YARN_APP_ID=#{appId} and YARN_ATTEMPT_ID=#{attemptId}")
  @ResultMap("jobLogResultMap")
  public JobLogMapping getJobLogByAppIdAndAttemptId(@Param("appId") String appId,
        @Param("attemptId") String attemptId);

  @Select("select * from JOB_LOG_MAPPING where YARN_APP_ID = #{jobLog.yarnAppId} "
        + " and LOG_DIR = #{jobLog.logDir}")
  @ResultMap("jobLogResultMap")
  public JobLogMapping getJobLogByAppIdAndLogDir(@Param("jobLog") JobLogMapping jobLog);

  @Select("select * from JOB_LOG_MAPPING where LOG_TYPE = 'YARNLOG' order by CREATE_TIME desc limit #{limit}")
  @ResultMap("jobLogResultMap")
  public List<JobLogMapping> getRecentYarnJobLogs(@Param("limit") int limit);

  @Select("select * from JOB_LOG_MAPPING where LOG_TYPE = 'YARNLOG' and YARN_APP_ID=#{appId} order by CREATE_TIME desc")
  public List<JobLogMapping> getYarnJobLogByAppId(@Param("appId") String appId);

  @Select("select * from JOB_LOG_MAPPING where LOG_TYPE = 'YARNLOG' and YARN_APP_ID=#{appId} order by CREATE_TIME desc limit 1")
  public JobLogMapping getYarnLatestJobLogByAppId(@Param("appId") String appId);

}
